<?php

function send_mail($emailaddress, $fromaddress, $emailsubject, $body, $name,$attachments=false)
{
  $eol="\r\n";
  $mime_boundary=md5(time());
 
  # Common Headers
  $headers .= 'From: '.$name.'<'.$fromaddress.'>'.$eol;
  $headers .= 'Reply-To: '.$name.'<'.$fromaddress.'>'.$eol;
  $headers .= 'Return-Path: '.$name.'<'.$fromaddress.'>'.$eol;    // these two to set reply address
  $headers .= "Message-ID: <".$now." bevshire@".$_SERVER['SERVER_NAME'].">".$eol;
  $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters

  # Boundry for marking the split & Multitype Headers
  $headers .= 'MIME-Version: 1.0'.$eol;
  $headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;

  $msg = "";     
 
  if ($attachments)
  {

    for($i=0; $i < count($attachments); $i++)
    {
      if (is_file($attachments[$i]["file"]))
      {  
        # File for Attachment
        $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
       
        $handle=fopen($attachments[$i]["file"], 'rb');
        $f_contents=fread($handle, filesize($attachments[$i]["file"]));
        $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
        fclose($handle);
       
        # Attachment
        $msg .= "--".$mime_boundary.$eol;
        $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;
        $msg .= "Content-Transfer-Encoding: base64".$eol;
        $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
        $msg .= $f_contents.$eol.$eol;
       
      }
    }
  }
 
  # Setup for text OR html
  $msg .= "Content-Type: multipart/alternative".$eol;
 
  # Text Version
  $msg .= "--".$mime_boundary.$eol;
  $msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
  $msg .= "Content-Transfer-Encoding: 8bit".$eol;
  $msg .= strip_tags(str_replace("<br>", "\n", $body)).$eol.$eol;
 
  # HTML Version
  $msg .= "--".$mime_boundary.$eol;
  $msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
  $msg .= "Content-Transfer-Encoding: 8bit".$eol;
  $msg .= $body.$eol.$eol;
 
  # Finished
  $msg .= "--".$mime_boundary."--".$eol.$eol;  // finish with two eol's for better security. see Injection.
   
  # SEND THE EMAIL
  ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
  mail($emailaddress, $emailsubject, $msg, $headers);
  ini_restore(sendmail_from);
  echo "mail send";
  return '1';
}


/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */

$name = $HTTP_POST_VARS['name'];
$email = $HTTP_POST_VARS['email'];
$message = $HTTP_POST_VARS['message'];
$to  = "bev@bevs-hire.co.nz";  // here we set the email to the address we want it to go to.
$spam_to = "spam@bevs-hire.co.nz";

// Strip \r and \n and a bunch of other naughty characters from the email address

  $pattern = '/(;|\||`|>|<|&|^|"|'."\r|'".'|{|}|[|]|\)|\()/i'; // no piping, passing possible environment variables ($),
                           // seperate commands, nested execution, file redirection,
                           // background processing, special commands (backspace, etc.), quotes
                           // newlines, or some other special characters
  
  $pattern2 = '/(;|\||`|&|^|"|'."\r|'".'|{|}|[|]|\)|\()/i';  //allow new lines and html                     
  
  $name = preg_replace($pattern, "", $name);
  $email = preg_replace($pattern, "", $email);
  $message = preg_replace($pattern2, "", $message);

// Remove injected headers
$find = array("/bcc\:/i","/Content\-Type\:/i","/cc\:/i","/to\:/i");
$email = preg_replace($find, "**bogus header removed**", $email);
$message = preg_replace($find, "**bogus header removed**", $message);
$name = preg_replace($find, "**bogus header removed**", $name);

$find_bogus = "**bogus header removed**";

// setting address to another address.
// this way we can never lose an email,
// know when dumbheads are messing with us,
// and not bother clients with this sort of thing


  if(stristr($message, $find_bogus) !== FALSE) {
        $to = $spam_to;  }

  if(stristr($name, $find_bogus) !== FALSE) {
        $to = $spam_to;
}

  if(stristr($email, $find_bogus) !== FALSE) {
        $to = $spam_to;
}


$sendthis = "NAME\n$name \n\nEMAIL\n$email \n\nMESSAGE\n$message"; // compose the message      

/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */
if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$", $email)) {
  echo "<h2 style=\"color: red;\">It appears you entered an invalid email address</h2>";
  echo "<p><a href='javascript: history.go(-1)'>Please go back and enter a valid email address.</a></p>";
} elseif (!trim($name)) {
  echo "<h2 style=\"color: red;\">Please go back and enter a name</h2>";
  echo "<p><a href='javascript: history.go(-1)'>Click here to go back</a>.</p>";
}

 elseif (!trim($message)) {
  echo "<h2 style=\"color: red;\">Please go back and type a message</h2>";
  echo "<p><a href='javascript: history.go(-1)'>Click here to go back</a>.</p>";
}

 elseif (!trim($email)) {
  echo "<h2 style=\"color: red;\">Please go back and enter an email</h2>";
  echo "<p><a href='javascript: history.go(-1)'>Click here to go back</a>.</p>";
}


// Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise.
elseif (send_mail($to,$email,"Contact via website - ".$name,$sendthis,$name)) {
  echo "<h2>Thank You</h2><p>We will be in touch as soon as possible.</p>";
echo<<<END
        <p>$email</p>
        <p>$message</p>
        <p>$name</p>
        <p>$to</p>
		<a href="http://bevs-hire.co.nz">Back to Bev's Hire</a>
END;
} else {
  echo "<h4>An unknown error occured. Please try again.</h4>";
}
?>